import numpy
import os
import cv2
from PIL import Image, ImageDraw, ImageFont
from moviepy.editor import VideoFileClip
import ProcessSrt

#导出视频中的音频
def extract_audio(video_file,audio_file):
    video_clip = VideoFileClip(video_file)
    audio = video_clip.audio
    audio.write_audiofile(audio_file)
    audio.close()
    video_clip.close()
    return audio_file

# 首先使用 os.path.getsize() 函数获取视频文件的大小（以字节为单位）
# 然后使用 get_video_duration() 函数获取视频的时长（以秒为单位）
# 最后，我们将文件大小乘以8（将单位从字节转换为比特）除以视频时长，来计算视频的比特率。
def get_video_bitrate(file_path):
    file_size = os.path.getsize(file_path) # 获取视频文件大小，单位是字节
    video_duration = VideoFileClip(file_path).duration # 获取视频时长，单位是秒
    video_bitrate = file_size * 8 / video_duration # 比特率的单位是 bps（比特每秒）
    return int(video_bitrate)

#合并视频中的音频到另外一个视频文件中
def merge_audio(video_audio_file,video_file,dest_merged_file):    
    video_audio_clip = VideoFileClip(video_audio_file)
    audio = video_audio_clip.audio
    bitrate = get_video_bitrate(video_audio_file)
    video_clip = VideoFileClip(video_file)
    video_merge_clip = video_clip.set_audio(audio)
    video_merge_clip.write_videofile(dest_merged_file,codec="libx264",bitrate=str(bitrate))
    video_merge_clip.close()
    video_clip.close()
    audio.close()
    video_audio_clip.close()
    return dest_merged_file

def add_title(src_video_file,blur_yaixs,blur_heigh,srt_file,font_file,font_size,font_color,title_xaisx,title_yaixs,bySpace,out_video_file):
    capture = cv2.VideoCapture(src_video_file)
    used_font = ImageFont.truetype(font_file, font_size, encoding="utf-8")
    #虚化位置
    bx,by,bw,bh = 0,blur_yaixs,int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)),blur_heigh
    #字幕位置,字幕高度自动
    tx,ty,tw = title_xaisx,title_yaixs,int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))-2*title_xaisx
    #字幕处理，字幕换行
    subtitles = ProcessSrt.parser_srt(srt_file,"utf-8")
    for subtitle in subtitles:   
        tmp = ProcessSrt.truncat_srt(subtitle[2],used_font,tw,bySpace)
        subtitle[2].clear()
        subtitle[2].extend(tmp)
    #写入部分
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    fps = capture.get(cv2.CAP_PROP_FPS)
    video_writer = cv2.VideoWriter(out_video_file, fourcc, fps, (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))))

    #按帧处理
    ret,frame= capture.read()
    while ret:
        #高斯虚化
        roi = frame[by:by+bh, bx:bx+bw]
        blurred = cv2.GaussianBlur(roi, (25, 25), 1000)
        frame[by:by+bh, bx:bx+bw] = blurred
        #增加字幕
        for start_millisecond, end_millisecond, texts in subtitles:
            if start_millisecond <= capture.get(cv2.CAP_PROP_POS_MSEC) <= end_millisecond:
                if (isinstance(frame, numpy.ndarray)):  #判断是否OpenCV图片类型
                    frame = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
                draw = ImageDraw.Draw(frame)
                offy = ty                    
                for text in texts : 
                    draw.text((tx + (tw-used_font.getlength(text))/2, offy), text, fill=font_color, font=used_font)
                    offy = offy + used_font.size + 5                        
                frame = cv2.cvtColor(numpy.asarray(frame), cv2.COLOR_RGB2BGR)
        video_writer.write(frame)
        ret, frame = capture.read()
    video_writer.release()
    capture.release()
    cv2.destroyAllWindows()